﻿using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace LegendHub.IO
{
    public static class SerializeManager
    {
        /// <summary>
        /// 将对象序列化为二进制
        /// </summary>
        /// <param name="uTarget">需要序列化的对象</param>
        /// <returns>二进制数组</returns>
        public static byte[] Serialize(object uTarget)
        {
            IFormatter formatter = new BinaryFormatter();//定义BinaryFormatter以序列化DataSet对象
            var ms = new MemoryStream();//创建内存流对象
            formatter.Serialize(ms, uTarget);//把DataSet对象序列化到内存流
            var buffer = ms.ToArray();//把内存流对象写入字节数组
            ms.Close();//关闭内存流对象
            ms.Dispose();//释放资源
            var ms2 = new MemoryStream();
            var gzipStream = new GZipStream(ms2, CompressionMode.Compress, true);//创建压缩对象
            gzipStream.Write(buffer, 0, buffer.Length);//把压缩后的数据写入文件
            gzipStream.Close();//关闭压缩流,这里要注意：一定要关闭，要不然解压缩的时候会出现小于4K的文件读取不到数据，大于4K的文件读取不完整
            gzipStream.Dispose();//释放对象
            var temp = ms2.ToArray();
            ms2.Close();
            ms2.Dispose();
            return temp;
        }

        /// <summary>
        /// 将二进制反序列化成对象
        /// </summary>
        /// <typeparam name="T">对象原类型</typeparam>
        /// <param name="uTarget">二进制数组</param>
        /// <returns>原对象</returns>
        public static T DeSerialize<T>(byte[] uTarget)
        {
            var ms = new MemoryStream(uTarget) { Position = 0 };
            //设置文件流的位置
            var gzipStream = new GZipStream(ms, CompressionMode.Decompress);//创建解压对象
            var buffer = new byte[4096];//定义数据缓冲
            int offset;//定义读取位置
            var ms2 = new MemoryStream();//定义内存流
            while ((offset = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                ms2.Write(buffer, 0, offset);//解压后的数据写入内存流
            }
            var sfFormatter = new BinaryFormatter();//定义BinaryFormatter以反序列化DataSet对象
            ms2.Position = 0;//设置内存流的位置
            T obj;
            try
            {
                obj = (T)sfFormatter.Deserialize(ms2);//反序列化
            }
            finally
            {
                ms2.Close();//关闭内存流
                ms2.Dispose();//释放资源
            }
            ms.Close();//关闭文件流
            ms.Dispose();//释放资源
            gzipStream.Close();//关闭解压缩流
            gzipStream.Dispose();//释放资源
            return obj;
        }
    }
}